package view;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.*;

import domain.Question;
import service.QuestionService;
import util.BaseFrame;
import util.MySpring;

public class ExamFrame extends BaseFrame {
	
	//先获取题目，QuestionService对象
	QuestionService service = MySpring.getBean("service.QuestionService");
	//通过service调用getPaper方法获取一套随机生成的试卷  题数自己定义
	ArrayList<Question> paper = service.getPaper(5);
	//创建一个用于存储学生选择答案的容器  String[paper.size()]
	private String[] answers = new String[paper.size()];
	
	private int nowNum = 0;
	private int totalCount = paper.size();
	private int answerCount = 0;
	private int unanswerCount = totalCount;
	
	//创建一个线程对象  控制时间变化
	private TimeControlThread timeControlThread = new TimeControlThread();
	private int time = 5;

//	for(int i=0;i<paper.size();i++) {
//		Question question = paper.get(i);
//		String title = question.getTitle().replace("<br>", "\n   ");
//		System.out.println((i+1)+"、"+title);
//	}
	
//===============================================================================
	//添加属性--组件
	//方法-->属性设置 字体 背景 位置 布局 等
	//方法-->添加到窗体中
	//方法-->添加事件监听
	//方法-->窗体自己的信息设置
	
	public ExamFrame() {
		this.init();
	}
	public ExamFrame(String title) {
		super(title);
		this.init();
	}
	
	private JPanel mainPanel = new JPanel();
	private JPanel messagePanel = new JPanel();
	private JPanel buttonPanel = new JPanel();
	private JTextArea examArea = new JTextArea();
	private JScrollPane scrollPane = new JScrollPane(examArea);
	private JLabel pictureLabel = new JLabel();
	private JLabel nowNumLabel = new JLabel("当前题号：");
	private JLabel totalCountLabel = new JLabel("题目总数：");
	private JLabel answerCountLabel = new JLabel("已答题数：");
	private JLabel unanswerCountLabel = new JLabel("未答题数：");
	private JTextField nowNumField = new JTextField();
	private JTextField totalCountField = new JTextField();
	private JTextField answerCountField = new JTextField();
	private JTextField unanswerCountField = new JTextField();
	private JLabel timeLabel = new JLabel("剩余答题时间");
	private JLabel realTimeLabel = new JLabel("00:00:00");
	private JButton aButton = new JButton("A");
	private JButton bButton = new JButton("B");
	private JButton cButton = new JButton("C");
	private JButton dButton = new JButton("D");
	private JButton preButton = new JButton("上一题");
	private JButton nextButton = new JButton("下一题");
	private JButton submitButton = new JButton("提交试卷");
	
	@Override
	protected void setFontAndSoOn() {
		mainPanel.setLayout(null);
		mainPanel.setBackground(Color.LIGHT_GRAY);
		messagePanel.setLayout(null);
		buttonPanel.setLayout(null);
		scrollPane.setBounds(16,10,650,450);
		examArea.setFont(new Font("微软雅黑",Font.BOLD,24));
		examArea.setEnabled(false);
		
		messagePanel.setBounds(680, 10, 300, 550);
		messagePanel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		
		buttonPanel.setBounds(16, 470, 650, 90);
		buttonPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		
		pictureLabel.setBounds(10, 10, 280, 230);
		pictureLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		nowNumLabel.setBounds(40, 270, 100, 30);
		nowNumLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
		nowNumField.setBounds(150, 270, 100, 30);
		nowNumField.setFont(new Font("微软雅黑",Font.BOLD,20));
		nowNumField.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		nowNumField.setEnabled(false);
		nowNumField.setHorizontalAlignment(JTextField.CENTER);
		
		totalCountLabel.setBounds(40, 310, 100, 30);
		totalCountLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
		totalCountField.setBounds(150, 310, 100, 30);
		totalCountField.setFont(new Font("微软雅黑",Font.BOLD,20));
		totalCountField.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		totalCountField.setEnabled(false);
		totalCountField.setHorizontalAlignment(JTextField.CENTER);
		
		answerCountLabel.setBounds(40, 350, 100, 30);
		answerCountLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
		answerCountField.setBounds(150, 350, 100, 30);
		answerCountField.setFont(new Font("微软雅黑",Font.BOLD,20));
		answerCountField.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		answerCountField.setEnabled(false);
		answerCountField.setHorizontalAlignment(JTextField.CENTER);
		
		unanswerCountLabel.setBounds(40, 390, 100, 30);
		unanswerCountLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
		unanswerCountField.setBounds(150, 390, 100, 30);
		unanswerCountField.setFont(new Font("微软雅黑",Font.BOLD,20));
		unanswerCountField.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		unanswerCountField.setEnabled(false);
		unanswerCountField.setHorizontalAlignment(JTextField.CENTER);
		
		timeLabel.setBounds(90, 460, 150, 30);
		timeLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
		timeLabel.setForeground(Color.RED);
		realTimeLabel.setBounds(110, 490, 150, 30);
		realTimeLabel.setFont(new Font("微软雅黑",Font.PLAIN,20));
		realTimeLabel.setForeground(Color.BLUE);
		
		aButton.setBounds(40, 10, 120, 30);
		aButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		bButton.setBounds(190, 10, 120, 30);
		bButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		cButton.setBounds(340, 10, 120, 30);
		cButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		dButton.setBounds(490, 10, 120, 30);
		dButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		preButton.setBounds(40, 50, 100, 30);
		preButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		preButton.setEnabled(false);
		nextButton.setBounds(510, 50, 100, 30);
		nextButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		submitButton.setBounds(276, 50, 100, 30);
		submitButton.setForeground(Color.RED);
		submitButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	
		//先展示第一道考试题目
		this.showQuestion();
		nowNumField.setText((nowNum+1)+"");
		totalCountField.setText(totalCount+"");
		answerCountField.setText(answerCount+"");
		unanswerCountField.setText(unanswerCount+"");
		realTimeLabel.setText(time+"");
	}

	@Override
	protected void addElement() {
		messagePanel.add(pictureLabel);
		messagePanel.add(nowNumLabel);
		messagePanel.add(nowNumField);
		messagePanel.add(totalCountLabel);
		messagePanel.add(totalCountField);
		messagePanel.add(answerCountLabel);
		messagePanel.add(answerCountField);
		messagePanel.add(unanswerCountLabel);
		messagePanel.add(unanswerCountField);
		messagePanel.add(timeLabel);
		messagePanel.add(realTimeLabel);
		buttonPanel.add(aButton);
		buttonPanel.add(bButton);
		buttonPanel.add(cButton);
		buttonPanel.add(dButton);
		buttonPanel.add(preButton);
		buttonPanel.add(nextButton);
		buttonPanel.add(submitButton);
		mainPanel.add(scrollPane);
		mainPanel.add(messagePanel);
		mainPanel.add(buttonPanel);
		this.add(mainPanel);
	}

	@Override
	protected void addListener() {
		
		preButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//清除所有按钮的颜色
				ExamFrame.this.clearOptionButtonColor();
				//还原四个选项按钮状态，变成可用的
				ExamFrame.this.setOptionButtonEnabled(true);
				nextButton.setEnabled(true);
				//当前题目序号减1
				nowNum--;
				//如果当前题号为0  已经到达第一题  让上一题按钮禁用
				if(nowNum==0) {
					preButton.setEnabled(false);
				}
				//还原之前这道题选择的是哪一个选项
				ExamFrame.this.restoreButton();
				ExamFrame.this.showQuestion();
				nowNumField.setText((nowNum+1)+"");
				answerCountField.setText(--answerCount+"");
				unanswerCountField.setText(++unanswerCount+"");

			}
			
		});
		
		nextButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//先清除所有选项按钮颜色
				ExamFrame.this.clearOptionButtonColor();
				//当前题目序号加1
				nowNum++;
				//当前题目是否到达最后
				if(nowNum==totalCount) {
					examArea.setText("全部题目已经回答完毕\n点击提交按钮提交试卷");
					//全部题目都回答完毕
					//让下一个题目按钮失效
					nextButton.setEnabled(false);
					//全部选项按钮失效
					ExamFrame.this.setOptionButtonEnabled(false);
				}else {
					if(nowNum!=0) {
						preButton.setEnabled(true);
					}
					//调用自己封装的方法显示下一题
					ExamFrame.this.restoreButton();
					ExamFrame.this.showQuestion();
					nowNumField.setText((nowNum+1)+"");
				}
				//修改右侧 已答题目和未答题目数
				answerCountField.setText(++answerCount+"");
				unanswerCountField.setText(--unanswerCount+"");
			}
			
		});
		
		
		ActionListener optionListener = new ActionListener() {//接口不能直接new创建对象，所以用匿名内部类
			@Override
			public void actionPerformed(ActionEvent e) {
				//清除之前所有选项按钮的颜色
				ExamFrame.this.clearOptionButtonColor();
				//让被点中的按钮颜色变化
				JButton button = (JButton)e.getSource();
				//让当前按钮颜色变化一下
				button.setBackground(Color.YELLOW);
				//将当前按钮的选项存储在answers数组中
				answers[nowNum] = button.getText();
			}
			
		};
		aButton.addActionListener(optionListener);
		bButton.addActionListener(optionListener);
		cButton.addActionListener(optionListener);
		dButton.addActionListener(optionListener);
		
		submitButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//弹出一个确认框
				int value = JOptionPane.showConfirmDialog(ExamFrame.this, "是否确认提交试卷？");
				if(value==0) {
					//倒计时时间停止---线程处理
					timeControlThread.stopTimeThread();
					//所有按钮失效
					ExamFrame.this.setOptionButtonEnabled(false);
					preButton.setEnabled(false);
					nextButton.setEnabled(false);
					submitButton.setEnabled(false);
					ExamFrame.this.clearOptionButtonColor();
					//最终成绩的计算 
					float score = ExamFrame.this.checkPaper();
					examArea.setText("考试结束\n\n"+ExamFrame.super.getTitle().split("的")[0]+",您的成绩为"+score+"分");
				}
			}
		});
	}

	@Override
	protected void setFrameSelf() {
		this.setCenterFrame(1008, 610);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(false);
		this.setVisible(true);
		timeControlThread.start();//窗体都加载完了  启动自己定义的线程对象  
	}
	
	//负责还原上一题的选项
	private void restoreButton() {
		//获取当前题目的答案
		String answer = answers[nowNum];
		if(answer==null) {
			return ;
		}
		switch(answer) {
			case "A":
				aButton.setBackground(Color.YELLOW);
				break;
			case "B":
				bButton.setBackground(Color.YELLOW);
				break;
			case "C":
				cButton.setBackground(Color.YELLOW);
				break;
			case "D":
				dButton.setBackground(Color.YELLOW);
				break;
			default:
				this.clearOptionButtonColor();
		}
	}
	
	//设计一个方法让所有选项按钮失效
	private void setOptionButtonEnabled(boolean key) {
		aButton.setEnabled(key);
		bButton.setEnabled(key);
		cButton.setEnabled(key);
		dButton.setEnabled(key);
	}
	
	
	//设计一个方法清除所有选项按钮颜色
	private void clearOptionButtonColor() {
		aButton.setBackground(null);
		bButton.setBackground(null);
		cButton.setBackground(null);
		dButton.setBackground(null);
	}
	
	//设计一个方法用来处理图片展示
	private ImageIcon drawImage(String path) {
		//通过给定的路径创建一个icon对象
		ImageIcon imageIcon = new ImageIcon(path);
		//设置imageIcon对象内的image属性
		imageIcon.setImage(imageIcon.getImage().getScaledInstance(280, 230, Image.SCALE_DEFAULT));
		//将设置好的imageIcon对象返回
		return imageIcon;
	}
	
	//设计一个方法用来展示一道题目
	private void showQuestion() {
		Question question = paper.get(nowNum);//题目 答案 图片，图片可能为空
		//解析题目
		String picture = question.getPicture();
		if(picture!=null) {
			pictureLabel.setIcon(this.drawImage("src//img//"+picture));
		}else {
			pictureLabel.setIcon(null);
		}
		examArea.setText((nowNum+1)+"."+question.getTitle().replace("<br>", "\n   "));
	}
	//计算最终成绩的方法
	private float checkPaper() {
		float score = 100;
		int size = paper.size();
		for(int i=0;i<size;i++) {
			Question question = paper.get(i);
			String realAnswer = question.getAnswer();
			if(!realAnswer.equals(answers[i])) {
				score-=(100/size);
			}
		}
		return score;
	}
	
	//设计一个内部类  处理时间倒计时问题
	private class TimeControlThread extends Thread{
		
		private boolean flag = true;//用来控制倒计时进行与否
		public void stopTimeThread() {
			this.flag = false;
		}
		public void run() {
			//time转化成  小时：分钟：秒
			int hour = time/60;
			int minute = time%60;
			int second = 0;
			while(flag) {
				//将小时 分钟 秒 三个变量进行拼串处理
				StringBuilder timeString = new StringBuilder();
				//处理小时
				if(hour>=0 && hour<10) {
					timeString.append("0");
				}
				timeString.append(hour);
				timeString.append(":");
				//处理分钟
				if(minute>=0 && minute<10) {
					timeString.append("0");
				}
				timeString.append(minute);
				timeString.append(":");
				//处理秒
				if(second>=0 && second<10) {
					timeString.append("0");
				}
				timeString.append(second);
				//操作realTimeLabel 处理时间的显示
				realTimeLabel.setText(timeString.toString());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if(second>0) {
					second--;
				}else{
					if(minute>0) {
						minute--;
						second=59;
					}else {
						if(hour>0) {
							hour--;
							minute=59;
							second=59;
						}else {
							realTimeLabel.setForeground(Color.RED);
							ExamFrame.this.setOptionButtonEnabled(false);
							nextButton.setEnabled(false);
							preButton.setEnabled(false);
							//时间到弹出一个消息框  请提交
							JOptionPane.showMessageDialog(ExamFrame.this, "考试时间结束，请提交试卷");
							break;
						}
					}
				}
			}
		}
	}
}
